package com.hxexp.weixin.aop.api;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * HPE API 切面Bean
 *
 * <p>
 * 用于处理HPE API被调用时的日志输出
 *
 * @author li.jiang
 *
 */
@Component
@Aspect
public class APIAspectBean {
    /**
     * 切入点
     */
    @Pointcut("execution(* com.hxexp.weixin.hpe.api..*(..))")
    public void aspect() { // NOSONAR
    }

    /**
     * 前置通知
     *
     * @param joinPoint
     *            切入点对象
     */
    @Before("aspect()")
    public void before(JoinPoint joinPoint) {
        APILogHelper.getLogger().info("API Log Start [ JoinPoint:{}, Thread:{}, {}ms ]", joinPoint.toString(), Thread.currentThread().getId(),
                System.currentTimeMillis());
        APILogHelper.logAPIParam(joinPoint);
    }

    /**
     * 后置通知
     *
     * @param joinPoint
     *            切入点对象
     */
    @After("aspect()")
    public void after(JoinPoint joinPoint) { // NOSONAR
    }

    /**
     * 后置返回通知
     *
     * @param joinPoint
     *            切入点对象
     * @param returnValue
     *            被切方法返回值
     */
    @AfterReturning(pointcut = "aspect()", returning = "returnValue")
    public void afterReturn(JoinPoint joinPoint, Object returnValue) {
        APILogHelper.logAPIResult(returnValue);
        APILogHelper.getLogger().info("API Log End [ JoinPoint:{}, Thread:{}, {}ms ]", joinPoint.toString(), Thread.currentThread().getId(),
                System.currentTimeMillis());
    }

    /**
     * 异常抛出通知
     *
     * @param joinPoint
     *            切入点对象
     * @param ex
     *            异常信息
     */
    @AfterThrowing(pointcut = "aspect()", throwing = "ex")
    public void afterThrow(JoinPoint joinPoint, Exception ex) {
        APILogHelper.logAPIException(joinPoint, ex);
    }
}
